#include <iostream>
#include <pthread.h>
#include <string>
#include<unistd.h>
#include<vector>
int sum = 1000;
// 使用全局的锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER; 
void *routine(void *arg)
{
    std::string name = (char *)arg;
while(1)
{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&gcond,&mutex);
    std::cout << name << " 计算: " << sum << std::endl;
        sum++;
        pthread_mutex_unlock(&mutex);

}





    // while (1)
    // {
    //     // 加锁
    //     pthread_mutex_lock(&mutex);
    //     if (sum > 0)
    //     {
    //         printf("%s sells sum:%d\n", id, sum);
    //         sum--;
    //         // 解锁
    //         pthread_mutex_unlock(&mutex);
    //     }
    //     else
    //     {
    //         // 解锁
    //         pthread_mutex_unlock(&mutex);
    //         break;
    //     }
    // }
     return nullptr;
}

int main()
{



    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, routine, (void *)"thread-1");
    pthread_create(&t2, nullptr, routine, (void *)"thread-2");
    pthread_create(&t3, nullptr, routine, (void *)"thread-3");
    pthread_create(&t4, nullptr, routine, (void *)"thread-4");
    sleep(3);
while(1)
{
    //pthread_cond_signal(&gcond); 
    pthread_cond_broadcast(&gcond);
    sleep(1);

}
    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
    return 0;

}
